package com.engine.common.util.TokenVerifyUtil;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.exception.InvalidTokenRuntimeException;
import com.engine.init.Globle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
@Slf4j
public class TokenVerifyUtil {

    private static AuthRedisUtil authRedisUtil;

    public static String tokenVerify(String token) throws Exception {
        switch (Globle.tokenConfig)
        {
            case 0:
                return "";
            case 1:
                return tokenVerifyByRedisGetAuthCo(token);
            case 2:
                return tokenVerifyByTokenTable(token);
            default:
                return "";
        }
    }

    public static String tokenVerifyByTokenTable(String token) {
        return "";
    }

    public static String tokenVerifyByRedisGetAuthCo(String token) throws Exception {
        String userId = JWTUtil.getUserId(token);
        if (userId == null)
            throw new InvalidTokenRuntimeException("token解析错误");
        String json = authRedisUtil.get(userId);
        if (!StringUtils.isEmpty(json))
            throw new InvalidTokenRuntimeException("token未登录");
        try {
            Map jsonMap = JSONObject.parseObject(json, Map.class);
            Map userInfo = (Map) jsonMap.get("userInfo");
            String access = ((String) userInfo.get("areaId")).replaceAll("0*$", "");
            return access;
        } catch (Exception e) {
            throw new InvalidTokenRuntimeException("解析AuthCo出错");
        }
    }

    @Autowired
    public void setRedisUtil(AuthRedisUtil authRedisUtil) {
        TokenVerifyUtil.authRedisUtil = authRedisUtil;
    }
}
